<template>
  <HeaderTitle title="检测货品交易报表"></HeaderTitle>
  <div class="prodTransInspectReportPage">
    <div class="searchBox">
      <div class="sbTitle">选择条件范围:</div>
      <div class="row searchReqBox items-center">
        <div class="col-12 col-sm-6 col-md-4 searchItem">
          <div class="row items-center" style="position: relative;">
            <span class="col-4">收货日期: </span>
            <div class="col-7">
              <q-input type="text" v-model="deliverDate" readonly class="date_form_to">
                <template v-slot:prepend>
                  <q-icon name="event" class="cursor-pointer">
                    <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                      <q-date v-model="showDate" range />
                    </q-popup-proxy>
                  </q-icon>
                </template>
              </q-input>
            </div>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 searchItem">
          <div class="row items-center">
            <span class="col-4">完成检测日期:</span>
            <div class="col-7">
              <q-input type="text" v-model="completeDate" readonly class="date_form_to">
                <template v-slot:prepend>
                  <q-icon name="event" class="cursor-pointer">
                    <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                      <q-date v-model="showDate1" range />
                    </q-popup-proxy>
                  </q-icon>
                </template>
              </q-input>
            </div>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 searchItem">
          <div class="row items-center">
            <span class="col-4">地 点: </span>
            <input class="col-7" v-model="source" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 searchItem">
          <div class="row items-center">
            <span class="col-4">部门名称: </span>
            <input class="col-7" v-model="dept" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 searchItem">
          <div class="row items-center">
            <span class="col-4">生产单号: </span>
            <input class="col-7" v-model="orderNo" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 searchItem">
          <div class="row items-center">
            <span class="col-4">工人编号: </span>
            <input class="col-7" v-model="workerCode" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 searchItem">
          <div class="row items-center">
            <span class="col-4">检测员编号: </span>
            <input class="col-7" v-model="checkerCode" />
          </div>
        </div>
      </div>
      <div class="row searchBtnBox">
        <q-btn color="purple-10" class="searchBtn" @click="search()"
          >搜寻</q-btn
        >
      </div>
    </div>
    <div v-if="showResult" class="resultBox">
      <div class="exportBtnBox">
        <q-btn
          color="blue-10"
          class="exportBtn"
          label="导出"
          @click="exportTable()"
        >
          <q-icon name="fa-solid fa-file-arrow-down" class="exportSVG" />
        </q-btn>
      </div>
      <div class="resultTbBox">
        <q-table
          flat
          bordered
          dense
          separator="cell"
          table-header-class="bg-grey-5"
          :rows="rtrows"
          :columns="rtcolumns"
          row-key="serial"
          class="resultTable"
          :pagination="{ rowsPerPage: 50 }"
        >
        <template v-slot:header-cell="props">
            <q-th @click="sortByCol(props.col.name)">
              {{ props.col.label }}
              <span v-if="sortCol&&props.col.name==sortCol.replace(/-/g, '')">
                  <q-icon v-if="sortCol[0]=='-'" name="arrow_downward"></q-icon>
                  <q-icon v-if="sortCol[0]!='-'" name="arrow_upward"></q-icon>
              </span>
            </q-th>
        </template>

        <template v-slot:body-cell-failReason="props">
          <q-td style="text-align: center;">
            <div v-for="(item, index) in props.value" :key="index">
              {{ item.reason }}
            </div>
          </q-td>
        </template>

        <template v-slot:body-cell-failUnit="props">
          <q-td style="text-align: center;">
            <div v-for="(item, index) in props.row.failReason" :key="index">
              {{ item.failUnit }}
            </div>
          </q-td>
        </template>

        <template v-slot:body-cell-failTotal="props">
          <q-td style="text-align: center;">
            <div v-for="(item, index) in props.row.failReason" :key="index">
              {{ item.failQty }}
            </div>
          </q-td>
        </template>

        <template v-slot:bottom="scope">
            <q-pagination
            style="margin-right: 5px;"
              v-model="currentPage"
              color="primary"
              :max="max"
              :max-pages="6"
              boundary-numbers
              activeDesign="unelevated"
              activeColor="purple"
            />

            <div style="display: flex; align-items: center; gap: 4px">
              <div style="display: flex; align-items: center; gap: 4px">
                <div>每页的行数:</div>
                <div>
                  <q-select
                    dense
                    options-dense
                    borderless
                    optionsCover
                    v-model="scope.pagination.rowsPerPage"
                    :options="[5, 10, 20, 50, 100]"
                    @update:model-value="onchange"
                  />
                </div>
                {{
                  scope.pagination.rowsPerPage * currentPage -
                  scope.pagination.rowsPerPage +
                  1 +
                  " - " +
                  (
                    scope.pagination.rowsPerPage * currentPage <=
                    total
                    ? 
                    scope.pagination.rowsPerPage * currentPage
                    : rtrows.length
                    ) +
                  " of " +
                  total
                }}
              </div>
            </div>
          </template>


        </q-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch,computed } from "vue";

import HeaderTitle from "src/components/HeaderTitle.vue";
import { useReportStore } from "src/stores/modules/reportStore";
import { useQuasar, Loading, exportFile } from "quasar";
import { useUserStore } from "src/stores/modules/userStore";
import { formatMyDate } from 'src/utils/dateUtils'

import { getQCTransactionReport,  exportQCTransactionReport} from 'src/services/reportService'

const $q = useQuasar()
const useReport = useReportStore();
const useUser = useUserStore()
// Search Requirements
const deliverDate = ref('');
const completeDate = ref('');
const site = ref('');
const dept = ref('');
const source = ref('');
const orderNo = ref('');
const workerCode = ref('');
const checkerCode = ref('');
const showResult = ref(false);

const currentPage = ref(1);
const rowsPerPage = ref(50);
const sortCol = ref(null);
const total = ref(0);
const max = ref(1);
const sortDirection = ref('desc');
const showDate = ref({ from: '', to: '' })
const showDate1 = ref({ from: '', to: '' })

watch(()=> showDate.value, (newValue) =>{
  if(newValue !== null){
    if(newValue.from){
      deliverDate.value = `${newValue.from} - ${newValue.to}`
    }else if(newValue){
      deliverDate.value = newValue
    }else{
      deliverDate.value = ''
    }
  }else{
    deliverDate.value = ''
    showDate.value = ''
  }
})
watch(()=> showDate1.value, (newValue) =>{
  if(newValue !== null){
    if(newValue.from){
      completeDate.value = `${newValue.from} - ${newValue.to}`
    }else if(newValue){
      completeDate.value = newValue
    }else{
      completeDate.value = ''
    }
  }else{
    completeDate.value = ''
    showDate1.value = ''
  }
})
const exportTable = async () => {
  console.log("downloading QC production file... ");
  
  const searchReq = 
    {
      deliverDate: showDate.value.from ? showDate.value.from : deliverDate.value,
      completeDate: showDate1.value.from ? showDate1.value.from : completeDate.value,
      deliverDateEnd: showDate.value.to ? showDate.value.to : deliverDate.value,
      completeDateEnd: showDate1.value.to ? showDate1.value.to : completeDate.value,
      dept: dept.value,
      source: source.value,
      orderNo: orderNo.value,
      workerCode: workerCode.value,
      checkerCode: checkerCode.value,
    }
  ;
  // for (let key in searchReq){
  //   if (searchReq[key] == ''){
  //     searchReq[key] = null
  //   }
  // }

  try {
    Loading.show()
    const res = await exportQCTransactionReport(
    searchReq, 
    useUser.currentDept.accID,
    )
    if (res.status==200){
      const filename = "QCtransaction.csv"
      // const filename = res.headers['content-disposition'].split('filename=')[1].replace(/"/g, '');

      const status = exportFile(filename, res.data, {
        encoding: 'utf-8',
        mimeType: 'text/csv;',
        byteOrderMark: '\uFEFF'
      })

      if (status!=true){
        $q.notify({
          message: '导出失败',
          color: 'negative',
          timeout: 2000,
          position: "center",
        })
      }else{
        $q.notify({
          message: '导出成功',
          color: 'positive',
          timeout: 2000,
          position: "center",
        })
      }

    }
  } catch (error) {
    console.log(error);
  }
  Loading.hide()
};

// Result Table
const rtcolumns = [
  {
    name: "serial",
    required: true,
    label: "序号",
    align: "left",
    field: (row) => row.serialNo+1,
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "deliverDate",
    align: "center",
    label: "收货日期",
    field: "deliverDate",
    format:(val)=>{
      return formatMyDate(val)
    },
    sortable: true,
  },
  {
    name: "completeDate",
    align: "center",
    label: "完成检测日期",
    field: "completeDate",
    // format:(val)=>{
    //   const arr = val.split('T')
    //   return arr[0]
    // },
    sortable: true,
  },
  {
    name: "source",
    align: "center",
    label: "地点",
    field: "source",
    sortable: true,
  },
  {
    name: "orderNo",
    align: "center",
    label: "生产单号",
    field: "orderNo",
    sortable: true,
  },
  {
    name: "designNo",
    align: "center",
    label: "设计编号",
    field: "designNum",
    sortable: true,
  },
  {
    name: "goldType",
    align: "center",
    label: "成色",
    field: "goldType",
    sortable: true,
  },
  { name: "qty", align: "center", label: "件数", field: "qty", sortable: true },
  {
    name: "stoneQty",
    align: "center",
    label: "石粒数",
    field: "stoneQty",
    sortable: true,
  },
  {
    name: "passQty",
    align: "center",
    label: "合格件数",
    field: "passQty",
    sortable: false,
  },
  {
    name: "failQty",
    align: "center",
    label: "不合格件数",
    field: "failQty",
    format:(val,row)=>{
      return row.qty-row.passQty
      // return row.failReason.length
    },
    sortable: false,
  },
  {
    name: "failReason",
    align: "center",
    label: "不合格原因",
    field: "failReason",
    sortable: false,
  },
  {
    name: "failTotal",
    align: "center",
    label: "不合格数量",
    // format:(val,row)=>{
    //   let count = 0
    //   for (let fail of row.failReason){
    //     count += fail.failQty
    //   }
    //   return count
    // },
    field: "failTotal",
    sortable: false,
  },
  {
    name: "failUnit",
    align: "center",
    label: "不合格数量单位",
    field: "failUnit",
    sortable: false,
  },
  {
    name: "dept",
    align: "center",
    label: "部门名称",
    field: "dept",
    sortable: true,
  },
  {
    name: "workerCode",
    align: "center",
    label: "工人编号",
    field: "workerCode",
    sortable: false,
  },
  {
    name: "workerName",
    align: "center",
    label: "工人姓名",
    field: "workerName",
    sortable: false,
  },
  {
    name: "checkerCode",
    align: "center",
    label: "检测员编号",
    field: "checkerCode",
    sortable: false,
  },
  {
    name: "checkerName",
    align: "center",
    label: "检测员姓名",
    field: "checkerName",
    sortable: false,
  },
  {
    name: "checkerRole",
    align: "center",
    label: "检测员身份",
    field: "checkerRole",
    sortable: false,
  },
];

// HARDCODE
const rtrows = ref([]);

// Function: Search Function
const search = async () => {
  console.log("search...");
  const searchReq = 
    {
      deliverDate: showDate.value.from ? showDate.value.from : deliverDate.value,
      completeDate: showDate1.value.from ? showDate1.value.from : completeDate.value,
      deliverDateEnd: showDate.value.to ? showDate.value.to : deliverDate.value,
      completeDateEnd: showDate1.value.to ? showDate1.value.to : completeDate.value,
      dept: dept.value,
      source: source.value,
      orderNo: orderNo.value,
      workerCode: workerCode.value,
      checkerCode: checkerCode.value,
    }
  ;
  for (let key in searchReq){
    if (searchReq[key] == ''){
      searchReq[key] = null
    }
  }
  const res = await getQCTransactionReport(
    searchReq, 
    useUser.currentDept.accID,
    currentPage.value,
    rowsPerPage.value,
    sortCol.value
    )
        console.log(res.data);
  if (res.data){
    rtrows.value = res.data.results
    total.value = res.data.count;
    max.value = Math.ceil(res.data.count / rowsPerPage.value);
    showResult.value = true;

  }else{
    $q.notify({
      message: data.message,
      color: 'negative'
    })
  }
  console.log("searchReq: ", searchReq);
};

watch(currentPage,(newCurrentPage)=>{
  console.log(currentPage);
  currentPage.value = newCurrentPage
  search()
})

function onchange(val){
  rowsPerPage.value = val
  currentPage.value = 1
  search()
}

function sortByCol(col){
  console.log(col);
  if (sortCol.value==null){
    sortCol.value = col
  }
  sortCol.value = sortCol.value[0] == '-' ? col: '-' + col
  console.log(sortCol.value);
  search()
}
</script>
<style>
.date_form_to .q-field__control{
  height: 34.8px;
  background-color: #fff;
  border: 1px solid #ccc;
}
.date_form_to .q-field__marginal{
  height: 34.8px;
}
.date_form_to.q-field--standard .q-field__control:before{
  display: none;
}
.date_form_to{
  font-size: 18px;
  font-weight: bold;
  border: 1px solid #5f5b5b;
}
</style>
<style lang="scss" scoped>
.prodTransInspectReportPage {
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 20px;
  font-size: 1rem;
  @media (max-width: 480px) {
    font-size: 1rem;
  }
  .searchBox {
    background-color: #d8dff4;
    padding: 10px 10px 10px 10px;
    border-radius: 5px;
    width: 100%;
    .sbTitle {
      font-weight: bold;
      color: #1100bc;
    }
    .searchReqBox {
      background-color: #acbadf;
      padding: 10px 10px 10px 10px;
      font-size: 1.2rem;
      @media (max-width: 480px) {
        font-size: 1rem;
      }
      span {
        font-weight: bold;
        margin-right: 5px;
        color: #6727cf;
      }
      .searchItem {
        margin-top: 5px;
      }
    }
    .searchBtnBox {
      width: 100%;
      margin-top: 10px;
      text-align: center;
      .searchBtn {
        width: 30%;
        margin-left: auto;
        margin-right: auto;
      }
    }
  }
  .resultBox {
    width: 100%;
    margin-top: 10px;
    .exportBtnBox {
      margin-left: 10px;
      text-align: right;
      .exportBtn {
        font-size: 1rem;
        .exportSVG {
          margin-left: 5px;
        }
      }
    }
    .resultTable {
      margin-top: 10px;
    }
  }
}

::v-deep(.q-table__bottom) {
  justify-content: right !important;
}
</style>
